<template>
  <div class="community-page">
    <div class="container-fluid p-4">
      <div class="row">
        <div class="col-lg-8">
          

          <el-card class="mb-4" shadow="never">
            <div class="d-flex justify-content-between align-items-center mb-3">
              <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
                <el-menu-item index="1">最新动态</el-menu-item>
              </el-menu>
              <el-button v-if="!userStore.isAdmin" type="primary" :icon="Edit" @click="createPostModalVisible = true">发布新帖</el-button>
            </div>

            <div class="filter-controls d-flex gap-3 mb-3">
              <el-input placeholder="按标题和内容搜索..." v-model="searchKeyword" @keyup.enter="applyFilters" clearable
                class="flex-grow-1">
                <template #prepend>
                  <el-select v-model="selectedSection" placeholder="所有板块" clearable style="width: 130px;">
                    <el-option v-for="section in sections" :key="section.id" :label="section.name"
                      :value="section.id" />
                  </el-select>
                </template>
              </el-input>
              <el-button type="primary" :icon="Search" @click="applyFilters">搜索</el-button>
              <el-button @click="resetFilters">重置</el-button>
            </div>
          </el-card>

          <PostList :current-user-id="userStore.user?.id" :posts="formattedPosts" @view-post="showPostDetail"
            @delete-post="handleDeleteRequest" v-loading="loading" />

          <!-- <CreatePostModal v-model="createPostModalVisible" @post-created="applyFilters" />
          <PostList :current-user-id="userStore.user?.id" :posts="sortedAndFormattedPosts" @view-post="showPostDetail"
            v-loading="loading" /> -->
        </div>

        <!-- <div class="col-lg-4">
          <CommunitySidebar />
        </div> -->
      </div>
    </div>

    <CreatePostModal v-model="createPostModalVisible" @post-created="applyFilters" />
    <PostDetailModal :current-user-id="userStore.user?.id" v-model="postDetailDialogVisible" :post="currentThread"
      @delete-reply="handleDeleteReplyRequest" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue';
import { Search, Edit } from '@element-plus/icons-vue';
import { useForumStore } from '@/stores/forum.js';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox } from 'element-plus';
import webSocketService from '@/util/webSocketService.js'; // 导入 WebSocket 服务
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';
// 新增/修改行
import { useUserStore } from '@/stores/user.js';
const userStore = useUserStore();
// 导入新创建的组件
import CreatePostModal from '@/components/alert/community/CreatePostModal.vue';
import PostDetailModal from '@/components/alert/community/PostDetailModal.vue';
import CommunitySidebar from '@/components/community/CommunitySidebar.vue';
import PostList from '@/components/community/PostList.vue';
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

const forumStore = useForumStore();
// 使用 storeToRefs 保持响应性
const { posts, loading, currentThread, sections } = storeToRefs(forumStore);

// 状态
const activeIndex = ref('1');
const searchQuery = ref('');
const createPostModalVisible = ref(false);
const postDetailDialogVisible = ref(false);

const searchKeyword = ref('');
const selectedSection = ref(null);

// 方法
const handleSelect = (key) => {
  console.log('Selected tab:', key);
  refreshPosts();
};

// 4. 新增时间格式化函数
const formatRelativeTime = (timeStr) => {
  const postTime = dayjs(timeStr);
  const now = dayjs();
  const diffInMinutes = now.diff(postTime, 'minute');

  if (diffInMinutes < 1) {
    return '刚刚';
  }
  if (diffInMinutes < 60) {
    return `${diffInMinutes}分钟前`;
  }

  // dayjs fromNow() 默认会处理好其他情况 (如 "1小时前", "1天前")
  return postTime.fromNow();
};

const formattedPosts = computed(() => {
  if (!Array.isArray(posts.value)) return [];

  // 搜索接口返回的数据结构为 { forumPost: {...}, ... }，我们需要解构出 forumPost
  return posts.value
    .map(item => {
      const post = item.forumPost; // 关键改动：获取嵌套的帖子对象
      if (!post) return null; // 添加一个安全检查

      const hasValidUpdateTime = post.updateTime && post.updateTime > post.createTime;
      const sortTime = hasValidUpdateTime ? post.updateTime : post.createTime;

      return {
        ...post,
        sortTimestamp: new Date(sortTime).getTime(),
        timeAgo: formatRelativeTime(post.createTime),
        updatedAgo: hasValidUpdateTime ? `更新于 ${formatRelativeTime(post.updateTime)}` : null
      };
    })
    .filter(Boolean) // 过滤掉可能为null的项
    .sort((a, b) => b.sortTimestamp - a.sortTimestamp);
});
// Community.vue

// ++ 新增：处理删除回复的请求 ++
const handleDeleteReplyRequest = (reply) => {
  if (userStore.isAdmin) {
    // 管理员删除逻辑
    ElMessageBox.prompt('请输入删除该回复的原因：', '管理员操作', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '删除原因不能为空'
    }).then(({ value }) => {
      // 调用管理员专用的删除接口
      forumStore.deleteReplyAsAdmin(reply.id, value, () => {
        // 成功后刷新帖子详情
        forumStore.fetchPostThread(reply.postId);
      });
    }).catch(() => {
      ElMessage.info('已取消删除');
    });
  } else {
    // 作者自己删除的逻辑
    ElMessageBox.confirm('您确定要删除这条回复吗？', '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      forumStore.deleteReply(reply.id, () => {
        // 成功后刷新帖子详情
        forumStore.fetchPostThread(reply.postId);
      });
    });
  }
};
// 3. 新增计算属性，用于排序和格式化帖子列表
const sortedAndFormattedPosts = computed(() => {
  // 确保 posts.value 是一个数组
  if (!Array.isArray(posts.value)) {
    return [];
  }
  return posts.value
    .map(post => {
      // 检查 updateTime 是否存在且有效
      const hasValidUpdateTime = post.updateTime && post.updateTime > post.createTime;
      // 决定用于排序的时间戳
      const sortTime = hasValidUpdateTime ? post.updateTime : post.createTime;

      return {
        ...post,
        sortTimestamp: new Date(sortTime).getTime(), // 创建一个用于排序的时间戳
        timeAgo: formatRelativeTime(post.createTime), // 创建时间的相对时间
        // 如果有更新，创建更新时间的相对时间文本；否则为 null
        updatedAgo: hasValidUpdateTime ? `更新于 ${formatRelativeTime(post.updateTime)}` : null
      };
    })
    .sort((a, b) => {
      // 使用新的 sortTimestamp 属性进行逆序排序
      return b.sortTimestamp - a.sortTimestamp;
    });
});

// 新增：处理从其他页面跳转过来的导航请求
const handleNavigation = () => {
  const target = forumStore.navigationTarget;
  if (target && target.postId) {
    // 1. 临时存储要高亮的回复ID
    if (target.replyId) {
      sessionStorage.setItem('highlightReplyId', target.replyId);
    }
    
    // 2. 打开帖子详情
    forumStore.fetchPostThread(target.postId, (postData) => {
      postDetailDialogVisible.value = true;
    });

    // 3. 清除 store 中的目标，防止刷新页面时重复触发
    forumStore.clearNavigationTarget();
  }
};

const showPostDetail = (post) => {
  forumStore.unsubscribeFromTopic('main');
  // webSocketService.unsubscribe('main'); // 直接调用 service
  // 定义成功后的回调逻辑
  const onFetchSuccess = () => {
    // 订阅当前帖子的主题，以便实时接收新回复
    forumStore.subscribeToTopic(post.id);
    // webSocketService.subscribe(post.id); // 直接调用 service
    postDetailDialogVisible.value = true;
  };

  // 调用 store 的 action，并传入 postId 和成功回调
  forumStore.fetchPostThread(post.id, onFetchSuccess);
};

// const refreshPosts = () => {
//   forumStore.fetchPosts({ pageSize: -1 });
// };

const applyFilters = () => {
  const params = {
    pageSize: -1, // 按接口要求，不分页
    pageNo: 1,
  };

  // 动态添加参数
  if (searchKeyword.value) {
    params.keyWord = searchKeyword.value;
  }
  if (selectedSection.value) {
    params.sectionId = selectedSection.value;
  }

  // 调用 store 中已有的 searchPosts action
  forumStore.searchPosts(params);
};

// --- 新增：重置筛选的方法 ---
const resetFilters = () => {
  searchKeyword.value = '';
  selectedSection.value = null;
  applyFilters(); // 重置后重新加载全量数据
};

// 定义新帖子处理器
const handleNewPost = (postData) => {
  console.log('正在处理新帖子消息:', postData);
  // 检查帖子是否已存在于列表中，防止重复添加
  const isExist = posts.value.some(p => p.forumPost && p.id === postData.postId);
  if (!isExist) {
    // 创建正确的嵌套结构
    posts.value.unshift({
      forumPost: { // <--- 关键：所有数据都应包裹在 forumPost 对象内
        id: postData.postId,
        authorId: postData.authorId,
        title: postData.title,
        content: postData.content,
        createTime: postData.createTime,
        updateTime: null,
        isDelete: 0,
        isFeatured: 0,
        // ...其他必要的默认字段
      },
      replyList: [] // 新帖子回复列表为空
    });
    ElMessage.success('收到一条新帖子！');
  }
};
// 定义帖子更新处理器
const handleUpdatePost = (postData) => {
  console.log('正在处理更新帖子消息:', postData);
  const postIndex = posts.value.findIndex(p => p.forumPost && p.forumPost.id === postData.postId);
  if (postIndex !== -1) {
    // 更新列表中的帖子数据
    posts.value[postIndex].title = postData.title;
    posts.value[postIndex].content = postData.content;
  }
  // 如果详情弹窗打开且是当前帖子，也更新它
  if (currentThread.value && currentThread.value.forumPost.id === postData.postId) {
    currentThread.value.forumPost.title = postData.title;
    currentThread.value.forumPost.content = postData.content;
  }
};

// --- 新增方法 ---
// const handleDeleteRequest = (postId) => {
//   ElMessageBox.confirm(
//     '您确定要删除这篇帖子吗？此操作不可撤销。',
//     '警告',
//     {
//       confirmButtonText: '确定删除',
//       cancelButtonText: '取消',
//       type: 'warning',
//     }
//   ).then(() => {
//     // 用户点击了“确定”
//     forumStore.deletePost(postId).then(() => {
//       ElMessage({
//         type: 'success',
//         message: '删除成功',
//       });
//       // 注意：WebSocket 的 handleDeletePost 处理器会自动从列表移除帖子，
//       // 所以这里不需要手动操作 posts.value
//     }).catch((error) => {
//       // API 调用失败
//       ElMessage({
//         type: 'error',
//         message: `删除失败: ${error.message}`,
//       });
//     });
//   }).catch(() => {
//     // 用户点击了“取消”或关闭了弹窗
//     ElMessage({
//       type: 'info',
//       message: '已取消删除',
//     });
//   });
// };
const handleDeleteRequest = (postId) => {
  if (userStore.isAdmin) {
    // 管理员删除逻辑
    ElMessageBox.prompt('请输入删除原因：', '管理员操作', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      inputPattern: /.+/, // 确保原因不为空
      inputErrorMessage: '删除原因不能为空'
    }).then(({ value }) => {
      // 调用管理员专用的删除接口
      forumStore.deletePostAsAdmin(postId, value);
    }).catch(() => {
      ElMessage.info('已取消删除');
    });
  } else {
    // 作者自己删除的逻辑
    ElMessageBox.confirm('您确定要删除这篇帖子吗？此操作不可撤销。', '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      forumStore.deletePost(postId);
    });
  }
};

// --- 新增方法结束 ---

// 定义帖子删除处理器
const handleDeletePost = (postData) => {
  console.log('正在处理删除帖子消息:', postData);
  posts.value = posts.value.filter(p => p.forumPost && p.forumPost.id !== postData.postId);
};

const handleNewReply = (replyData) => {
  if (!currentThread.value || currentThread.value.forumPost.id !== replyData.postId) {
    return; // 如果当前没在看这个帖子，直接忽略
  }
  // 检查当前是否正在查看这个帖子
  if (currentThread.value && currentThread.value.forumPost.id === replyData.postId) {
    console.log('实时更新评论:', replyData);

    // 确保 replyList 存在
    if (!currentThread.value.replyList) {
      currentThread.value.replyList = [];
    }

    // 检查评论是否已存在，防止重复添加
    const isExist = currentThread.value.replyList.some(r => r.id === replyData.replyId);
    if (!isExist) {
      // 将后端返回的 replyData 构造成前端需要的格式
      const newReply = {
        id: replyData.replyId,
        postId: replyData.postId,
        fromReply: replyData.fatherId || null, // API用fatherId，我们内部用fromReply
        authorId: replyData.authorId,
        content: replyData.content,
        isTutorReply: replyData.isTutorReply,
        isBest: replyData.isBest,
        // createTime: replyData.createTime,
        createTime: new Date().toISOString(),
        isDelete: 0
      };
      currentThread.value.replyList.push(newReply);
    }
  }
};


watch(postDetailDialogVisible, (isVisible) => {
  if (!isVisible && currentThread.value && currentThread.value.forumPost) {
    forumStore.unsubscribeFromTopic(currentThread.value.forumPost.id);
    forumStore.subscribeToTopic('main');
    //webSocketService.unsubscribe(currentThread.value.forumPost.id); // 直接调用 service
    // 2. 重新订阅主页的主题
    // webSocketService.subscribe('main'); // 直接调用 service
  }
});

onMounted(() => {
  //refreshPosts();
  applyFilters(); // 修改：首次加载时调用新方法
  forumStore.fetchSections(); // 新增：获取板块列表用于下拉菜单
  forumStore.fetchMessages({ pageSize: -1 });
  // 用户进入社区主页时，订阅主页主题，以实时接收新帖子
  // 连接 WebSocket 并注册处理器
  webSocketService.connect();
  webSocketService.on('new_post', handleNewPost);
  webSocketService.on('update_post', handleUpdatePost);
  webSocketService.on('delete_post', handleDeletePost);
  webSocketService.on('reply', handleNewReply);
  webSocketService.on('reply_of_reply', handleNewReply); // 回复的回复也用同一个处理器
  webSocketService.on('reply_replied', handleNewReply);
  webSocketService.on('post_replied', handleNewReply);
  forumStore.subscribeToTopic('main');
  handleNavigation();
});

onUnmounted(() => {
  // 组件卸载时，注销处理器并断开连接
  webSocketService.off('new_post', handleNewPost);
  webSocketService.off('update_post', handleUpdatePost);
  webSocketService.off('delete_post', handleDeletePost);
  webSocketService.off('reply', handleNewReply);
  webSocketService.off('reply_of_reply', handleNewReply);
  webSocketService.off('reply_replied', handleNewReply);
  webSocketService.off('post_replied', handleNewReply);
  webSocketService.disconnect();
  if (currentThread.value && currentThread.value.forumPost && postDetailDialogVisible.value) {
    // 如果离开页面时详情弹窗是打开的
    forumStore.unsubscribeFromTopic(currentThread.value.forumPost.id);
    //webSocketService.unsubscribe(currentThread.value.forumPost.id);
  } else {
    // 如果离开页面时在看主列表
    forumStore.unsubscribeFromTopic('main');
    //webSocketService.unsubscribe('main');
  }
  webSocketService.disconnect();
});


</script>

<style scoped>
@import "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css";
@import "https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css";

@media (max-width: 992px) {

  /* 在小屏幕上让筛选器垂直堆叠，而不是水平排列 */
  .filter-controls {
    flex-direction: column;
    align-items: stretch;
  }
}


.community-page {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.el-menu-demo {
  border-bottom: none;
  flex-grow: 1;
}

.row {
  display: flex;
  flex-wrap: wrap;
}

.col-lg-8 {
  width:100%;
}

.col-lg-4 {
  width: 33.33333333%;
}

/* 响应式调整 */
@media (max-width: 992px) {

  .col-lg-8,
  .col-lg-4 {
    width: 100%;
  }
}
</style>